package wili.attrMapping.core.del;

import java.util.Map;
import java.util.TreeMap;

import wili.c.Ca;
import wili.c.Misc9a;

/**
 * 
 * @author weilai2@163.com
 *
 */
abstract class MapConversion {
	TreeMap<String, Object> fMap, tMap;

	public MapConversion() {

	}

	public MapConversion setFromMap(Object... KVs) {
		setFromMap(Misc9a.mapOf(KVs));
		return this;
	}

	public MapConversion setFromMap(Map<String, Object> map) {
		this.fMap = new TreeMap<String, Object>(map);
		return this;
	}

	public MapConversion setTargetKeys(String... keys) {
		this.tMap = new TreeMap<String, Object>();
		for (String key : keys) {
			tMap.put(key, null);
		}
		return this;
	}

	public MapConversion(Map<String, Object> fromMap, String... targetKeys) {
		this.fMap = new TreeMap<String, Object>(fromMap);
		this.setTargetKeys(targetKeys);
	}

	public Map<String, Object> getTargetMap(int refresh) {
		if (refresh > 0 || tMap == null) {
			refreshTargetMap();
		}
		return tMap;
	}

	public MapConversion setTarget(String key, Object va) {
		tMap.put(key, va);
		return this;
	}

	@SuppressWarnings("unchecked")
	public <T> T valueOf(String key, T def) {
		Object ret = fMap.get(key);
		if (ret == null)
			return def;
		return (T) ret;
	}

	protected abstract void refreshTargetMap();

	public static void test() {
		MapConversion conv = new MapConversion() {

			@Override
			protected void refreshTargetMap() {
				Integer age = this.valueOf("age", -1);
				if (age < 8) {
					setTarget("group", "baby");
				} else if (age < 20) {
					setTarget("group", "yong");
				} else if (age < 30) {
					setTarget("group", "adult");
				} else {
					if (this.valueOf("favor", "").equals("sport")) {
						setTarget("group", "healthy");
					} else {
						setTarget("group", "oldMan");
					}
				}
				this.setTarget("favor", this.valueOf("favor", "?"));

			}

		};
		conv.setFromMap("age", 60, "favor", "sport").setTargetKeys("group", "favor");
		Map<String, Object> ret = conv.getTargetMap(1);
		Ca.log("ret=" + ret);

	}

	public static void main(String[] args) {
		test();
	}
}
